package com.dgz.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dgz.common.core.constants.Constants;
import com.dgz.common.core.domain.TableDataInfo;
import com.dgz.common.core.enums.ExamListType;
import com.dgz.common.core.enums.ResultCode;
import com.dgz.common.core.uitls.ThreadLocalUtil;
import com.dgz.common.security.exception.ServiceException;
import com.dgz.common.security.service.TokenService;
import com.dgz.friend.domain.exam.Exam;
import com.dgz.friend.domain.exam.dto.ExamQueryDto;
import com.dgz.friend.domain.exam.vo.ExamVO;
import com.dgz.friend.domain.user.UserExam;
import com.dgz.friend.manager.ExamCacheManager;
import com.dgz.friend.mapper.exam.ExamMapper;
import com.dgz.friend.mapper.user.UserExamMapper;
import com.dgz.friend.service.user.IUserExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/05/09/10:48
 * @Description:
 */
@Service
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private TokenService tokenService;


    @Autowired
    private ExamCacheManager examCacheManager;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public int enter(String token, Long examId) {
        // 判断是否符合报名条件
        Exam exam = examMapper.selectById(examId);
        if(exam == null) {
            throw new ServiceException(ResultCode.EXAM_NOT_EXISTS);
        }
        // 开始时间在当前时间之前 已经开赛
        if(exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
//        Long userId = tokenService.getUserId(token,secret);
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class); // 直接从ThreadLocal中获取userId
        // 判断用户是否已经报名
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if(userExam != null) {
            // 用户已经报名
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        examCacheManager.addUserExamCache(userId,examId);
        userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }

    // 先查询缓存 缓存key u:e:l:用户id  如果缓存能够查到 则直接返回缓存数据
    // 如果缓存没有查到 则查询数据库 并将数据同步到redis中 并返回数据
    @Override
    public TableDataInfo list(ExamQueryDto examQueryDto) {
// 从redis中获取 列表数据数量
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        examQueryDto.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        List<ExamVO> examVOList;
        if(total == null || total <= 0) {
            PageHelper.startPage(examQueryDto.getPageNum(), examQueryDto.getPageSize());
            // 从数据库中查询我的竞赛列表
            examVOList = userExamMapper.selectUserExamList(userId);
            // 刷新缓存
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(),userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            // 从redis中获取 列表数据
            examVOList = examCacheManager.getExamVOList(examQueryDto,userId);
            total = examCacheManager.getListSize(examQueryDto.getType(), userId);
        }
        if(CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList,total);
    }
}
